package com.wuhunyu.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wuhunyu.commonutils.result.CommonResult;
import com.wuhunyu.entity.UserDetail;
import com.wuhunyu.servicebase.exception.Assert;
import com.wuhunyu.servicebase.result.ResponseUtil;
import com.wuhunyu.entity.SecurityUser;
import com.wuhunyu.security.TokenManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录过滤器
 * @author wuhunyu
 */
@Slf4j
public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter {

    private AuthenticationManager authenticationManager;

    private TokenManager tokenManager;

    private RedisTemplate redisTemplate;

    public TokenLoginFilter(AuthenticationManager authenticationManager, TokenManager tokenManager, RedisTemplate redisTemplate) {
        this.authenticationManager = authenticationManager;
        this.tokenManager = tokenManager;
        this.redisTemplate = redisTemplate;
        this.setPostOnly(false);
        this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/acl/login","POST"));
    }

    /**
     * 获取表单中的用户名和密码并返回
     * @param req
     * @param res
     * @return
     */
    @Override
    public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res) {
        UserDetail userDetail = null;
        try {
            userDetail = new ObjectMapper().readValue(req.getInputStream(), UserDetail.class);
        } catch (IOException e) {
            Assert.isRight(true, "认证异常");
        }
        return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(userDetail.getUsername(), userDetail.getPassword(), new ArrayList<>()));
    }

    /**
     * 登录成功
     * @param req
     * @param res
     * @param chain
     * @param auth
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain, Authentication auth) {
        SecurityUser user = (SecurityUser) auth.getPrincipal();
        // 将用户名信息封装成token字符串
        String token = tokenManager.createToken(user.getCurrentUserInfo().getUsername());
        // 将用户信息存入redis中，key为用户名，value为用户的权限列表
        redisTemplate.opsForValue().set(user.getCurrentUserInfo().getUsername(), user.getPermissionValueList());
        // 将token字符串返回给页面
        Map<String, Object> map = new HashMap<>(16);
        map.put("wuhunyu_token", token);
        log.info("登录成功");
        ResponseUtil.out(res, CommonResult.success("登录成功", map));
    }

    /**
     * 登录失败
     * @param request
     * @param response
     * @param e
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) {
        log.error("登录失败");
        ResponseUtil.out(response, CommonResult.error("登录失败"));
    }
}
